<template>
  <div class="app-container" v-loading="loading">
    <el-card class="box-card" shadow="false">
      <div style="padding: 10px 20px 10px 20px; background: #fff">
        <el-tabs v-model="activeName" @tab-click="handleClick">
          <el-tab-pane label="前台角色" name="1"></el-tab-pane>
          <el-tab-pane label="后台角色" name="2"></el-tab-pane>
        </el-tabs>
      </div>
      <div class="main">
        <div class="step1" v-if="activeName === '1'">
          <div class="left">
            <div style="display: flex; align-items: flex-start">
              <el-form
                ref="queryParamsFormRef"
                :model="queryParamsForm"
                label-width="80px"
                :inline="true"
              >
                <el-form-item label="角色名称" prop="roleName">
                  <el-input
                    v-model="queryParamsForm.roleName"
                    placeholder="请输入角色名称"
                    size="small"
                  ></el-input>
                </el-form-item>
                <el-form-item label="权限字符" prop="roleKey">
                  <el-input
                    v-model="queryParamsForm.roleKey"
                    size="small"
                    placeholder="请输入权限字符"
                  ></el-input>
                </el-form-item>
              </el-form>

              <el-button
                type="primary"
                size="small"
                icon="el-icon-search"
                @click="getListLeft"
                >查询</el-button
              >
              <el-button
                icon="el-icon-refresh-right"
                size="small"
                @click="() => handleResetLeft('queryParamsFormRef')"
                >重置</el-button
              >
            </div>
            <div class="leftTable">
              <el-table
                :data="roleList"
                border
                style="width: 100%"
                highlight-current-row
                @current-change="handleCurrentChange"
              >
                <el-table-column
                  prop="date"
                  label="序号"
                  width="80"
                  align="center"
                >
                  <template slot-scope="scope">
                    {{
                      (queryParamsForm.pageNum - 1) * queryParamsForm.pageSize +
                      (scope.$index + 1)
                    }}
                  </template>
                </el-table-column>
                <el-table-column
                  prop="roleName"
                  label="角色名称"
                  align="center"
                >
                </el-table-column>
                <el-table-column prop="roleKey" label="权限字符" align="center">
                </el-table-column>
                <el-table-column
                  prop="status"
                  label="状态"
                  align="center"
                  width="80"
                  :formatter="(row) => (row.status === '0' ? '正常' : '停用')"
                >
                </el-table-column>
              </el-table>
              <div class="pagination">
                <pagination
                  v-show="totalLeft > 0"
                  :total="totalLeft"
                  :page.sync="queryParamsForm.pageNum"
                  :limit.sync="queryParamsForm.pageSize"
                  @pagination="getListLeft"
                />
              </div>
            </div>
          </div>
          <div class="right">
            <div>
              <span>菜单权限：</span>
              <el-checkbox
                v-model="menuExpand"
                @change="handleCheckedTreeExpand($event, 'menu')"
                >展开/折叠</el-checkbox
              >
              <el-checkbox
                v-model="menuNodeAll"
                @change="handleCheckedTreeNodeAll($event, 'menu')"
                >全选/全不选</el-checkbox
              >
              <el-checkbox
                v-model="menuCheckStrictly"
                @change="handleCheckedTreeConnect($event, 'menu')"
                >父子联动</el-checkbox
              >
              <el-button
                type="primary"
                style="margin-left: 20px"
                size="small"
                icon="el-icon-document-checked"
                @click="save"
                >保存</el-button
              >
            </div>
            <div v-if="currentRow" style="margin-top: 20px">
              <el-tree
                :data="menuOptions"
                show-checkbox
                ref="menu"
                node-key="id"
                :check-strictly="!menuCheckStrictly"
                empty-text="暂无数据"
                :props="defaultProps"
              ></el-tree>
            </div>
          </div>
        </div>
        <div class="step2" v-if="activeName === '2'">
          <div class="left">
            <div style="display: flex; align-items: flex-start">
              <el-form
                ref="queryParamsFormRef"
                :model="queryParamsForm"
                label-width="80px"
                :inline="true"
              >
                <el-form-item label="角色名称" prop="roleName">
                  <el-input
                    v-model="queryParamsForm.roleName"
                    placeholder="请输入角色名称"
                    size="small"
                  ></el-input>
                </el-form-item>
                <el-form-item label="权限字符" prop="roleKey">
                  <el-input
                    v-model="queryParamsForm.roleKey"
                    placeholder="请输入权限字符"
                    size="small"
                  ></el-input>
                </el-form-item>
              </el-form>
              <el-button
                type="primary"
                size="small"
                icon="el-icon-search"
                @click="getListLeft"
                >查询</el-button
              >
              <el-button
                icon="el-icon-refresh-right"
                size="small"
                @click="() => handleResetLeft('queryParamsFormRef')"
                >重置</el-button
              >
            </div>
            <div class="leftTable">
              <el-table
                :data="roleList"
                border
                style="width: 100%"
                highlight-current-row
                @current-change="handleCurrentChange"
              >
                <el-table-column
                  prop="date"
                  label="序号"
                  width="80"
                  align="center"
                >
                  <template slot-scope="scope">
                    {{
                      (queryParamsForm.pageNum - 1) * queryParamsForm.pageSize +
                      (scope.$index + 1)
                    }}
                  </template>
                </el-table-column>
                <el-table-column
                  prop="roleName"
                  label="角色名称"
                  align="center"
                >
                </el-table-column>
                <el-table-column prop="roleKey" label="权限字符" align="center">
                </el-table-column>
                <el-table-column
                  prop="status"
                  label="状态"
                  align="center"
                  width="80"
                  :formatter="(row) => (row.status === '0' ? '正常' : '停用')"
                >
                </el-table-column>
              </el-table>
              <div class="pagination">
                <pagination
                  v-show="totalLeft > 0"
                  :total="totalLeft"
                  :page.sync="queryParamsForm.pageNum"
                  :limit.sync="queryParamsForm.pageSize"
                  @pagination="getListLeft"
                />
              </div>
            </div>
          </div>
          <div class="right">
            <div>
              <span>菜单权限：</span>
              <el-checkbox
                v-model="menuExpand"
                @change="handleCheckedTreeExpand($event, 'menu')"
                >展开/折叠</el-checkbox
              >
              <el-checkbox
                v-model="menuNodeAll"
                @change="handleCheckedTreeNodeAll($event, 'menu')"
                >全选/全不选</el-checkbox
              >
              <el-checkbox
                v-model="menuCheckStrictly"
                @change="handleCheckedTreeConnect($event, 'menu')"
                >父子联动</el-checkbox
              >
              <el-button
                type="primary"
                style="margin-left: 20px"
                size="small"
                icon="el-icon-document-checked"
                @click="save"
                >保存</el-button
              >
            </div>
            <div v-if="currentRow" style="margin-top: 20px">
              <el-tree
                :data="menuOptions"
                show-checkbox
                ref="menu"
                node-key="id"
                :check-strictly="!menuCheckStrictly"
                empty-text="暂无数据"
                :props="defaultProps"
              ></el-tree>
            </div>
          </div>
        </div>
      </div>
    </el-card>
  </div>
</template>

<script>
import {
  listRole,
  getRole,
  delRole,
  addRole,
  updateRole,
  dataScope,
  changeRoleStatus,
  deptTreeSelect,
  allocatedUserList,
  authUserCancel,
  authUserCancelAll,
} from "@/api/app/role";
import * as step2Api from "@/api/system/role";
import {
  treeselect as menuTreeselect,
  roleMenuTreeselect,
} from "@/api/system/menu";
import {
  listMenu,
  getMenu,
  delMenu,
  addMenu,
  updateMenu,
} from "@/api/system/menu";
export default {
  data() {
    return {
      activeName: "1",
      // 菜单列表
      menuOptions: [],
      menuExpand: true,
      menuNodeAll: false,
      menuCheckStrictly: true,
      loading: false,
      totalLeft: 0,
      roleList: [],
      queryParamsForm: {
        pageNum: 1,
        pageSize: 10,
      },
      currentRow: undefined,
      defaultProps: {
        children: "children",
        label: "label",
      },
    };
  },
  methods: {
    handleClick() {
      this.menuOptions = [];
      this.getListLeft();
    },
    // 所有菜单节点数据
    getMenuAllCheckedKeys() {
      // 目前被选中的菜单节点
      let checkedKeys = this.$refs.menu.getCheckedKeys();
      // 半选中的菜单节点
      let halfCheckedKeys = this.$refs.menu.getHalfCheckedKeys();
      checkedKeys.unshift.apply(checkedKeys, halfCheckedKeys);
      return checkedKeys;
    },
    async save() {
      const res = await getRole(this.currentRow?.roleId);
      const form = res.data;
      form.menuIds = this.getMenuAllCheckedKeys();
      const response = await updateRole(form);
      if (response.code === 200) {
        this.$modal.msgSuccess("保存成功");
        this.handleCurrentChange(this.currentRow);
      }
    },
    getListLeft() {
      this.loading = true;
      (this.activeName === "1"
        ? listRole(this.queryParamsForm)
        : step2Api.listRole(this.queryParamsForm)
      ).then((response) => {
        this.roleList = response.rows;
        this.totalLeft = response.total;
        this.loading = false;
      });
    },
    handleCurrentChange(row) {
      if (row.roleId === 1) {
        return this.$modal.msgError("不允许操作超级管理员角色");
      }
      this.currentRow = row;
      const roleId = row.roleId;
      const roleMenu = this.getRoleMenuTreeselect(roleId);
      const _this = this;
      this.$nextTick(() => {
        roleMenu.then((res) => {
          let checkedKeys = res.data.checkedKeys;
          checkedKeys.forEach((v) => {
            this.$nextTick(() => {
              this.$refs.menu.setChecked(v, true, false);
            });
          });
          _this.handleCheckedTreeExpand(true, "menu");
        });
      });
    },
    handleResetLeft(ref) {
      this.resetForm(ref);
      this.getListLeft();
    },
    // 树权限（展开/折叠）
    handleCheckedTreeExpand(value, type) {
      console.log(value, type);
      if (type == "menu") {
        let treeList = this.menuOptions;
        for (let i = 0; i < treeList.length; i++) {
          this.$refs.menu.store.nodesMap[treeList[i].id].expanded = value;
        }
      }
    },
    // 树权限（全选/全不选）
    handleCheckedTreeNodeAll(value, type) {
      if (type == "menu") {
        this.$refs.menu.setCheckedNodes(value ? this.menuOptions : []);
      }
    },
    // 树权限（父子联动）
    handleCheckedTreeConnect(value, type) {
      if (type == "menu") {
        this.menuCheckStrictly = value ? true : false;
      }
    },
    getRoleMenuTreeselect(roleId) {
       return roleMenuTreeselect(roleId, this.activeName === "1" ? "before" : undefined).then((response) => {
          this.menuOptions = response.data.menus;
          return response;
        });
    },
  },
  created() {
    this.getListLeft();
  },
};
</script>
<style lang="scss" scoped>
.app-container {
  padding: 10px;
  ::v-deep .el-card {
    background: #f1f1f1 !important;
    .el-card__body {
      padding: 0;
    }
    .el-form-item {
      margin-bottom: 10px;
    }
  }
  .main {
    .step1,
    .step2 {
      width: 100%;
      display: flex;
      justify-content: space-between;
      align-items: flex-start;
    }
    .left {
      background: #fff;
      width: 50%;
      margin-right: 10px;
      min-height: 85vh;
      padding: 10px 20px 10px 20px;
    }
    .right {
      background: #fff;
      width: 50%;
      min-height: 85vh;
      padding: 10px 20px 10px 20px;
    }
  }
}
</style>
